package edu.uow.devdocs

class ProjectController {
    static scaffold = true
	
	
	def update() {
		def projectInstance = Project.get(params.id)
		if (!projectInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: '${domainClass.propertyName}.label', default: 'Project'), params.id])
			redirect(action: "list")
			return
		}

		if (params.version) {
			def version = params.version.toLong()
			if (projectInstance.version > version) {
				projectInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
						  [message(code: 'project.label', default: 'Project')] as Object[],
						  "Another user has updated this Project while you were editing")
				render(view: "edit", model: [projectInstance: projectInstance])
				return
			}
		}
		def oldPersonIds = projectInstance.persons*.id

		bindData(projectInstance,params, [exclude: 'persons'])
		
		def newPersonIds = params?.list('persons')

		oldPersonIds.each {
			def p1 = Person.get(it)
			p1.removeFromProjects(projectInstance)
		}
		newPersonIds.each {
			if(it != 'null') {
				def p2 = Person.get(it)
				p2.addToProjects(projectInstance)
			}
		}
		
		if (!projectInstance.save(flush: true)) {
			render(view: "edit", model: [projectInstance: projectInstance])
			return
		}

		flash.message = message(code: 'default.updated.message', args: [message(code: 'project.label', default: 'Project'), projectInstance.id])
		redirect(action: "show", id: projectInstance.id)
	}
	
}
